package com.zhichan.jdunion_plugin

import android.util.Log
import androidx.annotation.NonNull
import com.zhichan.jdunion_plugin.helper.JdunionHelper

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** JdunionPlugin */
class JdunionPlugin: FlutterPlugin, MethodCallHandler, ActivityAware {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel

  private var jdunionHelper: JdunionHelper? = null

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    jdunionHelper = JdunionHelper()
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "jdunion_plugin")
    channel.setMethodCallHandler(this)
  }

  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
    Log.i("onMethodCall", "onMethodCall: " + call.method)
    when (call.method) {
      "initJdUnion" -> jdunionHelper?.init(call.arguments as String)
      "openJDAppByUrl" -> {
        val url = call.arguments as String
        jdunionHelper?.openJDAppByUrl(url, result)
      }
      "openJXAppByUrl" -> {
        val url = call.arguments as String
        jdunionHelper?.openJXAppByUrl(url, result)
      }
      "getPlatformVersion" -> result.success("Android ${android.os.Build.VERSION.RELEASE}")
      else -> result.notImplemented()
    }
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
    jdunionHelper?.setActivity(null)
    jdunionHelper = null
  }

  override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    jdunionHelper?.setActivity(binding.activity)
  }

  override fun onDetachedFromActivityForConfigChanges() {
    jdunionHelper?.setActivity(null)
  }

  override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    jdunionHelper?.setActivity(binding.activity)
  }

  override fun onDetachedFromActivity() {
    jdunionHelper?.setActivity(null)
  }
}
